import inputEventClient from '@ohos.multimodalInput.inputEventClient';
import { KeyCode } from '@ohos.multimodalInput.keyCode';
import { objType } from './utils'

let KeyDownOpt = {
    isPressed: true,
    keyCode: KeyCode.KEYCODE_UNKNOWN,
    keyDownDuration: 0,
    isIntercepted: false
}

let KeyUpOpt = {
    isPressed: false,
    keyCode: KeyCode.KEYCODE_UNKNOWN,
    keyDownDuration: 0,
    isIntercepted: false
};

function keyDown(){
    try {
        inputEventClient.injectEvent({ KeyEvent: KeyDownOpt });
    } catch (error) {
        console.log(`Failed to inject keyDown, error: ${JSON.stringify(error, [`code`, `message`])}`);
    }
}

function keyUp(){
    try {
        inputEventClient.injectEvent({ KeyEvent: KeyUpOpt });
    } catch (error) {
        console.log(`Failed to inject keyUp, error: ${JSON.stringify(error, [`code`, `message`])}`);
    }
}

export function tabKeyDown(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_TAB;
    keyDown();
}

export function tabKeyUp(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_TAB;
    keyUp();
}

export function tabClick(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_TAB;
    keyDown();
    keyUp();
}

export function leftKeyDown(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_LEFT;
    keyDown();
}

export function leftKeyUp(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_LEFT;
    keyUp();
}

export function leftClick(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_LEFT;
    keyDown();
    keyUp();
}

export function rightKeyDown(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_RIGHT;
    keyDown();
}

export function rightKeyUp(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_RIGHT;
    keyUp();
}

export function rightClick(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_RIGHT;
    keyDown();
    keyUp();
}

export function upKeyDown(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_UP;
    keyDown();
}

export function upKeyUp(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_UP;
    keyUp();
}

export function upClick(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_UP;
    keyDown();
    keyUp();
}

export function downKeyDown(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_DOWN;
    keyDown();
}

export function downKeyUp(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_DOWN;
    keyUp();
}

export function downClick(){
    KeyDownOpt.keyCode = KeyCode.KEYCODE_DPAD_DOWN;
    keyDown();
    keyUp();
}

export function bindKeyClick(obj){
    if(objType(obj) == 'object'){
        obj.leftClick = leftClick;
        obj.rightClick = rightClick;
        obj.upClick = upClick;
        obj.downClick = downClick;
        obj.tabClick = tabClick;
    }
}